package com.app.GoCuro;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.app.GoCuro.data.CurrentSession;
import com.app.GoCuro.data.InputItem;
import com.app.GoCuro.util.CustomHttpClient;
import com.app.GoCuro.util.IntentIntegrator;
import com.app.GoCuro.util.IntentResult;

public class DatabaseActionsActivity extends BaseActivity 
{
	
	private static final int BUTTON_POSITIVE = -1;
	private static final int BUTTON_NEGATIVE = -2;
	public static final int BUTTON_NEUTRAL = -3;
	
	ArrayAdapter<String> adapter;	//previous item list adapter
	LinkedList<String> itemsLinkedList = new LinkedList<String>();
	Map<String,InputItem> timeItemMap = new HashMap<String, InputItem>();
	ListView previousItemsList; 
	//int numofItems = 0;
	final int manualInput_RequestCode = 1;
	CustomHttpClient httpClient;
	
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		if(savedInstanceState != null){
			onRestoreInstanceState(savedInstanceState);  
		}
		
		setContentView(R.layout.database_actions);
		adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, itemsLinkedList);
    	previousItemsList = (ListView) findViewById(R.id.previous_items);
    	previousItemsList.setAdapter(adapter);
    	
    	httpClient = new CustomHttpClient(this);
		
		//add controller for button input here
		final Button inputButton = (Button) findViewById(R.id.enter_item);
		inputButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				//Start MannualInputActivity
				Intent MannualInputActivityIntent = new Intent(DatabaseActionsActivity.this, ManualInputActivity.class);
				DatabaseActionsActivity.this.startActivityForResult(MannualInputActivityIntent, manualInput_RequestCode);
			}
		});
		
		final Button scanButton = (Button) findViewById(R.id.scan_item);
		scanButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				//Call BarcodeScanner
				IntentIntegrator integrator = new IntentIntegrator(DatabaseActionsActivity.this);
				ArrayList<String> format = new ArrayList<String>();
				for(String s: IntentIntegrator.PRODUCT_CODE_TYPES){
					format.add(s);
				}
				for(String s: IntentIntegrator.ONE_D_CODE_TYPES){
					format.add(s);
				}
				for(String s: IntentIntegrator.QR_CODE_TYPES){
					format.add(s);
				}
				format.add("PDF_417");
				integrator.initiateScan(format);
			}
		});

		//
		//TODO: Get the items from web client here
		//
		
		final Button sendButton = (Button) findViewById(R.id.send_to_server);
		sendButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				// send the list of info objects to server
				
				final ProgressDialog pd_sendingToServer = new ProgressDialog(DatabaseActionsActivity.this);
				pd_sendingToServer.setTitle("Sending..");
				pd_sendingToServer.setMessage("Sending items to server...");
					
				pd_sendingToServer.show();
		
				// a dummy thread 
				final LinkedList<String> itemsLinkedList_copy =  (LinkedList<String>) itemsLinkedList.clone();
				
				Thread th_sendingToServer = new Thread()
				{    
					/*
					 * Insert the item into the server and hope for no crashes.
					 */
					@Override
					public void run() 
					{
						try 
						{
							
							for(int i = 0; i < itemsLinkedList_copy.size(); i++)
							{
								InputItem item = timeItemMap.get(itemsLinkedList_copy.get(i));
								httpClient.postNewItem(item);
							}
							
							sleep(1);
							
							
						} 
						catch (InterruptedException e)  
						{
							e.printStackTrace();
						} 
						finally 
						{
							pd_sendingToServer.dismiss();
						}
						
						
					}
				};
				th_sendingToServer.start();
				
				itemsLinkedList.clear();
				adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, itemsLinkedList);
		    	previousItemsList.setAdapter(adapter);
				
			} // end onClick
		}); // end setOnClickListener
		
		//get and set the databases string
		CurrentSession currSession = (CurrentSession) getApplicationContext();
		setTitle(currSession.getJobsite().getName());
		TextView database_items = (TextView) findViewById(R.id.database_name);
		database_items.setText(currSession.getJobsite().getName());

		previousItemsList.setOnItemClickListener(new OnItemClickListener()  {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) 
			{
				//start the new activity here, to be done in a future revision
				showListItem(arg1);
				
			}
		});
		
	} // end onCreat
	
	private void showListItem(View view) {
		
		int indexofFirstColon  = ((TextView) view).getText().toString().indexOf(":");
		// the is a space after the colon, so the starting index should +2 
		//final String datetime = ((TextView) view).getText().toString().substring(indexofFirstColon + 2);
		final String datetime = ((TextView) view).getText().toString();
		final InputItem selectedItem = timeItemMap.get(datetime);
		
		// simple way of displaying item in list
		//Toast.makeText(getApplicationContext(), selectedItem.toString(), Toast.LENGTH_SHORT).show();
		
		final AlertDialog ad_viewItem = new AlertDialog.Builder(DatabaseActionsActivity.this).create();
		
		ad_viewItem.setTitle("Item detail");
		ad_viewItem.setMessage((CharSequence)selectedItem.toString()) ;
		ad_viewItem.setButton(BUTTON_POSITIVE, "OK" ,new DialogInterface.OnClickListener() {
		      public void onClick(DialogInterface dialog, int which) {
		    	  ad_viewItem.dismiss();
		      } 
		});
		
		ad_viewItem.setButton(BUTTON_NEUTRAL, "Edit", new DialogInterface.OnClickListener() {
		      public void onClick(DialogInterface dialog, int which) {
		    	
		    	//Start MannualInputActivity, transfer it with selected item
		    	Intent MannualInputActivityIntent = new Intent(DatabaseActionsActivity.this, ManualInputActivity.class);
		    	Bundle manualInput_OldData = new Bundle();
		    	manualInput_OldData.putParcelable("oldDataItem",selectedItem);
		    	MannualInputActivityIntent.putExtras(manualInput_OldData);
				DatabaseActionsActivity.this.startActivityForResult(MannualInputActivityIntent, manualInput_RequestCode);
				
		      } 
		});
		
		ad_viewItem.setButton(BUTTON_NEGATIVE, "Delete", new DialogInterface.OnClickListener() {
		      public void onClick(DialogInterface dialog, int which) {
		    	
		    	// remove the selected item from list
		    	itemsLinkedList.remove(itemsLinkedList.indexOf(datetime));
		    	timeItemMap.remove(datetime);
		    	adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, itemsLinkedList);
				previousItemsList.setAdapter(adapter);
		      } 
		});
		
		ad_viewItem.show();  
	}
	
	// parse the scanner-return string from scanner
	// only parse itemName and itemQuan from the scanner-return string
	// barcode is set to empty string
	private InputItem parseScannedContents(String contents, String datetime) {
		
		int indexofRealContent_start = contents.indexOf("Contents:");
		int indexofRealContent_end = contents.indexOf("Raw");
		System.out.println(contents);
		contents = contents.substring(indexofRealContent_start + 9, indexofRealContent_end - 1);
		//Barcode must have ; to separate values!
		String itemName = contents.substring(0,contents.indexOf(";"));
		String barcode  = "0";
		String itemQuan = contents.substring(contents.indexOf(";")+1);
		
		String createDatetime = datetime; 
		String modifyDatetime = "";
		InputItem newScannedItem = new InputItem(createDatetime, modifyDatetime, itemName, itemQuan, barcode);
		
		return newScannedItem;
	}

	
	//Get scan result from ZXing
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent resultIntent )  {
		
		super.onActivityResult(requestCode, resultCode, resultIntent);
		
		// return from manualInputActivity
		if(requestCode == manualInput_RequestCode) {
		
			if (resultCode == RESULT_OK) {   
				Bundle manualInputData = resultIntent.getExtras();
				InputItem manualInputItem = manualInputData.getParcelable("manualInputItem_key");
				String createDatetime = manualInputItem.getCreateDateTime();
				String modifyDatetime = manualInputItem.getModifiedDateTime();
				String itemName = manualInputItem.getItemName();
				String itemQuan = manualInputItem.getQuantity();
				String itemBarcode = manualInputItem.getBarcode();
				manualInputData.clear();
				
				// if  manual input activity return newly-created data
				if(modifyDatetime.isEmpty()){
					//numofItems++;
					//itemsLinkedList.addFirst("Item" + numofItems + ": " + createDatetime);
					itemsLinkedList.addFirst(createDatetime);
					timeItemMap.put(createDatetime, new InputItem(createDatetime, modifyDatetime, itemName, itemQuan, itemBarcode));
				}
				// if  manual input activity return editted data
				else{
					timeItemMap.put(createDatetime, manualInputItem);
				}
				
				adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, itemsLinkedList);
				previousItemsList.setAdapter(adapter);
				
	        }   
		}
		
		IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, resultIntent);
		if(scanResult != null){	
			if ( scanResult.getContents() != null) {
			
				// handle scan result
				String contents = scanResult.toString();
				if (contents == null) {
					Toast.makeText(this, "Scan Failed", Toast.LENGTH_LONG).show();
				}
				
				// show the string result returned from scanner, for test use
				// Toast.makeText(this, contents, Toast.LENGTH_SHORT).show();
				
				Calendar c = Calendar.getInstance();
				SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				String createDatetime = f.format(c.getTime());
				
				//create the information object
				InputItem newData = parseScannedContents(contents, createDatetime);
				
				timeItemMap.put(createDatetime, newData);
				
				// populate list view
				//numofItems++;
				itemsLinkedList.addFirst(createDatetime);
				
				adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, itemsLinkedList);
				previousItemsList.setAdapter(adapter);
				

			}
		}
	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		
		// save the number of items
		//outState.putInt("numofItems", numofItems);
		
		// save the items list (on list view)
		ArrayList<String> itemsArrayList = new ArrayList<String>(itemsLinkedList);
		outState.putStringArrayList("itemsList", itemsArrayList);
		
		// save the hashmap<datatime, scannedcontents>
		ArrayList<String> keyList = new ArrayList<String>();
		ArrayList<InputItem> valueList = new ArrayList<InputItem>();
		
		for(Object s : timeItemMap.keySet().toArray())
			keyList.add(s.toString());
		
		for(InputItem s : timeItemMap.values())
			valueList.add(s);
		
		outState.putStringArrayList("keysList",keyList);
		outState.putParcelableArrayList("valuesList",valueList);
		
	}

	@Override
	public void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		//restore the relevant information
		//numofItems = savedInstanceState.getInt("numofItems");
		itemsLinkedList = new LinkedList<String>(savedInstanceState.getStringArrayList("itemsList"));
		// restore the hashmap<datatime, scannedcontents>
		int i = 0;
		for(String key : savedInstanceState.getStringArrayList("keysList")){
			timeItemMap.put(key,(InputItem) savedInstanceState.getParcelableArrayList("valuesList").get(i));
			i++;
		}
		
	}
	
}
